#include "poetry.h"

Poetry::Poetry(QObject *parent) : QObject(parent) {
    QFile file(":/res/poetry.json");
    if (!file.open(QIODevice::ReadOnly)) {
        qCritical() << "无法打开文件";
        return;
    }

    QTextStream in(&file);
    QString data = in.readAll();
    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());
    QJsonObject jsonObject = doc.object();
    QJsonArray poemsArray = jsonObject["poems"].toArray();

    for (const QJsonValue& value : poemsArray) {
        QJsonObject poemObject = value.toObject();
        QString title = poemObject["title"].toString();
        QString author = poemObject["author"].toString();
        QString content = poemObject["content"].toString();
        QString fullPoem = author + "：" + content;
        poems.append(fullPoem);
    }
}


Poetry::~Poetry() {

}

QString Poetry::getPoetry() {
    if (poems.isEmpty()) {
        return "没有可用的诗句";
    }

    int index;
    do {
        index = QRandomGenerator::global()->bounded(poems.size());
    } while (index == lastIndex);

    lastIndex = index;
    return poems[index];
}
